<template>
  <div>

    <!--    头部查询区-->
    <el-card style="margin-bottom: 8px">
      <el-row :gutter="20">
        <el-col :span="9">
          <el-input placeholder="关键字查询，范围:名称、型号、ip、参数、备注" v-model.trim="queryInfo.query" clearable
                    @change="clearKeywords">
            <el-button id="searchButton" slot="append" icon="el-icon-search" @click="getQueryList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <div class="areaSelect">
            <el-select @click.native="getuArealist()"
                       popper-class="areaSelect"
                       v-model="queryInfo.area"
                       placeholder="选择网络区域" clearable
                       @change="queryAreaSelectChange"
                       ref="template1">
              <!--                       @change="colorSelectChangeforid"-->
              <!--                       :popper-append-to-body="false"-->
              <!--                       @visible-change="v => visibleChange(v,'template1',  'ship')">-->
              <el-option v-for="item in arealist" :style="{background:item.yanse}" :key="item._id" :value="item._id"
                         :label="item.name">
              </el-option>
            </el-select>
          </div>

        </el-col>
        <el-col :span="3">
          <el-cascader v-model="requireType" :options="typeOptions" :props="{ checkStrictly: true }"
                       placeholder="选择设备类型" clearable
                       @change="typechange">
          </el-cascader>
        </el-col>
        <el-col :span="1">
          <el-tooltip content="新建设备">
            <el-button type="success" icon="el-icon-plus" circle @click="opendialog0"></el-button>
          </el-tooltip>
        </el-col>
        <el-col :span="1">
          <el-tooltip content="刷新列表">
            <el-button icon="el-icon-refresh" circle @click="refresh"></el-button>
          </el-tooltip>
        </el-col>
      </el-row>

    </el-card>

    <el-card>
      <!--      <el-button @click="open">打开</el-button>-->
      <!--      列表显示区-->
      <el-table :data="deviceList" border :header-cell-style="{'text-align':'center'}"
                :cell-style="{'text-align':'center'}"
                @row-click="ctdk"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                v-loading="fullscreenLoading">
        <el-table-column prop="area" label="区域" width="150">
          <template slot-scope="scope">
            <div v-if="scope.row.area">
              <el-tag :style="{background:scope.row.area.yanse ,color:'white'}">{{scope.row.area.name}}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="资产类型">
          <template slot-scope="scope">
            <div v-if="scope.row.type[0] === '硬件设备'">
              <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item v-for="(item,index) in scope.row.type" :key="index"><span style="color:#67C23A">{{item}}</span>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div v-if="scope.row.type[0] === '软件资产'">
              <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item v-for="(item,index) in scope.row.type" :key="index"><span style="color:#409EFF">{{item}}</span>
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <!--            <div v-if="scope.row.type[0] === '服务器'">-->
            <!--              <el-breadcrumb separator-class="el-icon-arrow-right">-->
            <!--                <el-breadcrumb-item v-for="(item,index) in scope.row.type" :key="index"><span style="color:#E6A23C">{{item}}</span>-->
            <!--                </el-breadcrumb-item>-->
            <!--              </el-breadcrumb>-->
            <!--            </div>-->
            <!--            <div v-if="scope.row.type[0] === '存储网络'">-->
            <!--              <el-breadcrumb separator-class="el-icon-arrow-right">-->
            <!--                <el-breadcrumb-item v-for="(item,index) in scope.row.type" :key="index"><span style="color:#F56C6C">{{item}}</span>-->
            <!--                </el-breadcrumb-item>-->
            <!--              </el-breadcrumb>-->
            <!--            </div>-->
            <!--            <div v-if="scope.row.type[0] === '机房设备'">-->
            <!--              <el-breadcrumb separator-class="el-icon-arrow-right">-->
            <!--                <el-breadcrumb-item v-for="(item,index) in scope.row.type" :key="index"><span style="color:#606266">{{item}}</span>-->
            <!--                </el-breadcrumb-item>-->
            <!--              </el-breadcrumb>-->
            <!--            </div>-->

          </template>
        </el-table-column>
        <el-table-column prop="name" label="资产名称"></el-table-column>
        <el-table-column prop="xinhao" label="资产型号"></el-table-column>
        <el-table-column prop="ip" label="IP地址">
          <template slot-scope="scope">
            <span v-for=" ip in scope.row.ip" :key="ip" style="margin-right: 10px">{{ip}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="parameter" label="参数配置">
          <template slot-scope="scope">
            <span
              style="white-space: nowrap;   overflow: hidden;  text-overflow: ellipsis;">{{scope.row.parameter}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="parameter" label="备注说明">
          <template slot-scope="scope">
            <span
              style="white-space: nowrap;   overflow: hidden;  text-overflow: ellipsis;">{{scope.row.beizhu}}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="admin" label="操作" width="150">
          <template  slot-scope="scope">
            <!--复制按钮-->
            <el-tooltip effect="dark" content="复制" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-document-copy" size="mini" @click="copyRow(scope.row)"
                         onClick="event.cancelBubble = true" circle></el-button>
            </el-tooltip>
            <!--修改按钮-->
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="success" icon="el-icon-edit" size="mini" @click="openedit(scope.row)"
                         onClick="event.cancelBubble = true" circle></el-button>
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip style="margin-left: 5px" effect="dark" content="删除" placement="top" :enterable="false">
              <el-popconfirm title="确定删除吗？" @confirm="deleteDevice(scope.row)">
                <el-button type="danger" icon="el-icon-delete" slot="reference" size="mini"
                           onClick="event.cancelBubble = true" circle></el-button>
              </el-popconfirm>

            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--      分页区域-->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.page"
          :page-sizes="[20,50,100]"
          :page-size="queryInfo.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="resdata.total">
        </el-pagination>
      </div>
    </el-card>

    <!--    新增设备弹框-->
    <el-dialog style="padding: 0" title="新增资产" :visible.sync="dialogVisible0" :append-to-body="true">
      <device_detail ref="device_detail" show="form" :deviceData="tableRow" :arealist="arealist"></device_detail>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible0 = false">取 消</el-button>
    <el-button type="primary" @click="addDevice">新 增</el-button>
  </span>
    </el-dialog>
    <!--    修改设备弹框-->
    <el-dialog style="padding:0" title="修改资产信息" :visible.sync="dialogVisible1" @close="getdeviceList">
      <device_detail ref="device_edit" show="edit" :deviceData="tableRow" :arealist="arealist"></device_detail>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible1 = false">取 消</el-button>
    <el-button type="primary" @click="editDevice">修 改</el-button>
  </span>
    </el-dialog>

    <!--    行数据查询抽屉-->
    <el-drawer
      title="标题"
      :visible.sync="drawer"
      :with-header="false"
      size="50%">
      <device_detail show="view" :deviceData="tableRow"></device_detail>
    </el-drawer>
  </div>
</template>

<script>
  import TestView from '~/components/test.vue';
  import device_detail from '~/components/device-detail.vue';

  export default {
    middleware: 'metaTitle',
    meta: {title: '资产清单'},
    name: "device",
    components: {TestView, device_detail},
    data() {
      return {
        admin: false,
        drawer: false,
        requireType: [],
        arealist: [],
        input: '',
        dialogVisible0: false,
        dialogVisible1: false,
        tableRow: '',
        fullscreenLoading: true,
        queryInfo: {
          query: '',
          area: '',
          type: '',
          page: 1,
          limit: 20,
        },
        resdata: "",
        deviceList: [],
        typeOptions: [{
          value: '硬件设备', label: "硬件设备", children: [{
            value: '网络设备', label: "网络设备",
            children: [{value: '交接机', label: "交接机"}, {value: '路由器', label: "路由器"},]
          },
            {
              value: '安全设备', label: "安全设备", children: [
                {value: '防火墙', label: "防火墙"},
                {value: 'IPS', label: "IPS"},
                {value: '防毒墙', label: "防毒墙"},
                {value: 'WAF', label: "WAF"},
                {value: '数据库审计', label: "数据库审计"},
                {value: '日志审计', label: "日志审计"},]
            },

            {value: '服务器', label: "服务器"},
            {
              value: '存储网络',
              label: "存储网络",
              children: [{value: '磁盘阵列柜', label: "磁盘阵列柜"}, {value: '存储光交换机', label: "存储光交换机"}, {
                value: '备份一体机',
                label: "备份一体机"
              },]
            },
            {
              value: '机房设备',
              label: "机房设备",
              children: [{value: '机房空调', label: "机房空调"}, {value: 'UPS主机', label: "UPS主机"}, {
                value: '动环设备',
                label: "动环设备"
              },]
            },]
        },
          {
            value: '软件资产',
            label: "软件资产",
            children: [{value: '虚拟机', label: "虚拟机"}, {value: '数据库', label: "数据库"}, {value: '中间件', label: "中间件"},
              {value: '管理软件', label: "管理软件"}, {value: '安全类软件', label: "安全类软件"}, {value: '业务软件', label: "业务软件"}]
          }]

      }
    },
    created() {
      this.fullscreenLoading = true
      if (this.$store.state.user.data.result.rank == 1) this.admin = true
      this.getdeviceList();
    },
    watch: {},
    methods: {
      refresh() {
        // window.location.reload() //这是窗口刷新
        this.fullscreenLoading = true;
        setTimeout(async () => {
          await this.getdeviceList();
          this.fullscreenLoading = false;
          // async ()=>{
          //   await this.getdeviceList();
          //   this.fullscreenLoading = false;
          // }
        }, 300);
      },
      async addDevice() {
        // let validate = this.$refs.device_detail.validate;
        //先清空数据
        if (this.$refs['device_detail'].validateForm()) {
          try {
            const res = await this.$axios.post('/api/device', this.$refs.device_detail.deviceForm);
            if (res.status === 200 && res.data.code === "ValidationError") {
              this.$message.error("设备名称重复")
            }
            if (res.status === 200 && res.data.code === "success") {
              this.$message.success("提交成功")
              this.dialogVisible0 = false
              this.getdeviceList();
            }
          } catch (e) {
            this.$message.error('连接服务器失败')
          }

        } else {
          return this.$message.error('请输入正确后提交');
        }


      },
      async editDevice() {
        //先表单验证
        if (this.$refs['device_edit'].validateForm()) {
          try {
            //先去除文件附件项，因为已经提交过了的，当前显示的列表没有实际BIN文件
            delete this.$refs.device_edit.deviceForm.files
            const res = await this.$axios.put('/api/device/' + this.$refs.device_edit.deviceForm._id, this.$refs.device_edit.deviceForm);
            if (res.status === 200 && res.data.code === "ValidationError") {
              this.$message.error("设备名称重复")
            }
            if (res.status === 200 && res.data.code === "success") {
              this.$message.success("提交成功")
              this.dialogVisible1 = false
              this.getdeviceList();
            }
          } catch (e) {
            this.$message.error('连接服务器失败')
          }
        }
      },
      async deleteDevice(row) {
        try {
          const res = await this.$axios.delete('/api/device/' + row._id, row);
          if (res.status === 200 && res.data.code === "success") {
            this.$message.success("删除成功")
            this.getdeviceList();
          }
        } catch (e) {
          this.$message.error('操作失败')
        }
      },
      //打开新增窗口
      opendialog0() {
        this.dialogVisible0 = true
        this.tableRow = {}

      },
      async getdeviceList() {
        try {
          const {data: res} = await this.$axios.get('/api/device', {params: this.queryInfo}).catch(error => {
            this.$message.error(error)
          });

          this.resdata = res.result
          this.deviceList = this.resdata.docs
          this.fullscreenLoading = false
          //console.log(this.deviceList)
        } catch (e) {

        }

      },
      //点击行显示详情
      ctdk(row) {
        this.drawer = true
        this.tableRow = row

      },
      async getuArealist() {
        const res = await this.$axios.get('/api/iparea').catch(eror => {
          this.$message.error(eror)
        })
        if (res.status === 200 && res.data.code === 'success') {
          this.arealist = res.data.result
          //this.$refs['device_detail'].arealist = res.data.result
        }
      },
      async copyRow(row) {
        // console.log(row)
        this.dialogVisible0 = true
        await this.getuArealist()
        this.tableRow = JSON.parse(JSON.stringify(row))
        if (this.tableRow.area) this.tableRow.area = this.tableRow.area._id
        delete this.tableRow._id
        if (this.tableRow.files) delete this.tableRow.files
        // console.log(this.tableRow)
      },
      async openedit(row) {
        this.dialogVisible1 = true
        await this.getuArealist()
        this.tableRow = JSON.parse(JSON.stringify(row))
        //console.log(this.tableRow)
        if (this.tableRow.area) this.tableRow.area = this.tableRow.area._id
        //this.tableRow = row
      },
      async typechange(type) {
        this.queryInfo.type = type
        const {data: res} = await this.$axios.get('/api/device', {params: this.queryInfo}).catch(
          (error) => {
            this.$message.error(error)
          })
        this.resdata = res.result
        this.deviceList = this.resdata.docs
      },
      async getQueryList() {
        const {data: res} = await this.$axios.get('/api/device', {params: this.queryInfo}).catch(
          (error) => {
            this.$message.error(error)
          })
        this.resdata = res.result
        this.deviceList = this.resdata.docs
      },

      clearKeywords() {
        if (this.queryInfo.query === '') {
          this.getQueryList()
        }
      },
      // 监听pagesize改变事件
      handleSizeChange(newSize) {
        // console.log(`每页 ${newSize} 条`)
        this.queryInfo.limit = newSize
        this.getdeviceList()
      },
      // // 监听页码改变
      handleCurrentChange(newPage) {
        // console.log(`当前页: ${newPage}`)
        this.queryInfo.page = newPage
        this.getdeviceList()
      },
      //设置颜色选择框中颜色
      setSelectColor(color, ref) {
        //通过操作dom节点改变样式
        this.$nextTick(() => {
          //let dom = this.$refs.colorSelect;
          let dom = this.$refs[ref];
          if (dom) {
            dom = dom.$el.children[0];
            let inputDom = dom.querySelectorAll(".el-input__inner");
            let icon = dom.querySelectorAll(".el-input__icon");
            inputDom[0].style["background-color"] = color;
            icon[0].style["color"] = "black";
          }
        })
      },
      colorSelectChange(val) {

        this.setSelectColor(val, 'colorSelect');
        //触发update事件更新父组件绑定值
        this.$emit('update', val);
      },
      colorSelectChangeforid(val) {
        let item = this.arealist.find(item => item._id === val)
        this.setSelectColor(item.yanse, 'template1');
        //触发update事件更新父组件绑定值
        this.$emit('update', item.yanse);
      },
      //触发查询网络区域
      async queryAreaSelectChange(value) {
        // const {data: res} = await this.$axios.get('/api/iptable', {params: this.queryInfo}).catch(error => {
        //   this.$message.error(error)
        // });
        // //console.log(res.result.docs)
        // if (res.code === "success") this.iplistData = res.result.docs
        this.getQueryList()
      },
    },
  }
</script>

<style lang="less" scoped>

  #searchButton:active {
    background: #DCDFE6;
  }

  .yanseSelect {
    color: white;
    width: 100%;

    /deep/ .el-select-dropdown__item.selected {
      color: white;
    }
  }

  .areaSelect {
    margin-right: 20px;

    .el-select-dropdown__item.selected {
      color: white;
    }

  }
</style>
